package com.museum.core.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;


@Component
public class RedisUtil {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private RedisTemplate redisTemplate;
	/**
	 * 存放string类型
	 *
	 * @param key
	 *            key
	 * @param data
	 *            数据
	 * @param timeout
	 *            超时间
	 */
	public void setString(String key, String data, Long timeout) {
		try {
			stringRedisTemplate.opsForValue().set(key, data);
			if (timeout != null) {
				stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
			}

		} catch (Exception e) {

		}

	}
	/**
	 * @param
	 * @Desciption 放置对象
	 * @return
	 */
	public void setObject(String key, Object object, Long timeout) {
		try {
			if (timeout != null) {
				redisTemplate.expire(key, timeout, TimeUnit.SECONDS);
			}
			redisTemplate.opsForValue().set(key,object);
//			System.out.println("自定义的数据是"+ redisTemplate.opsForValue().get("1133"));
//			System.out.println("key是"+key);
//			userInfo  o = (userInfo)redisTemplate.opsForValue().get(ple.getUserId());
			System.out.println(getObject(key));
		} catch (Exception e) {

		}
	}
	public void setObject(String key, Object object) {
		try {
			System.out.println("输入参数="+object+"token=="+key);
			redisTemplate.opsForValue().set(key, object);
			Object o = redisTemplate.opsForValue().get(key);
			System.out.println("输出+"+o);
		} catch (Exception e) {

		}
	}
	/**
	 * 开启Redis 事务
	 *
	 */
	public void begin() {
		// 开启Redis 事务权限
		stringRedisTemplate.setEnableTransactionSupport(true);
		// 开启事务
		stringRedisTemplate.multi();

	}
	/**
	 * 提交事务
	 *
	 */
	public void exec() {
		// 成功提交事务
		stringRedisTemplate.exec();
	}

	/**
	 * 回滚Redis 事务
	 */
	public void discard() {
		stringRedisTemplate.discard();
	}
	/**
	 * 存放string类型
	 *
	 * @param key
	 *            key
	 * @param data
	 *            数据
	 */
	public void setString(String key, String data) {
		setString(key, data, null);
	}

	/**
	 * 根据key查询string类型
	 *
	 * @param key
	 * @return
	 */
	public String getString(String key) {
		String value = stringRedisTemplate.opsForValue().get(key);
		return value;
	}
	public Object getObject(String key) {
		return redisTemplate.opsForValue().get(key);
	}
	/**
	 * 根据对应的key删除key
	 *
	 * @param key
	 */
	public Boolean delKey(String key) {
		return stringRedisTemplate.delete(key);

	}
	public Boolean delObj(String key){
		return redisTemplate.delete(key);
	}
}

